package com.cn.codebrush.数组.双指针;

import java.util.Arrays;

/**
 * @Author Boolean
 * @Date 2022/4/22 10:48
 * @Version 1.0
 */
public class No16最接近的三数之和 {
    public static void main(String[] args) {
        int[] nums4 = {-1,2,1,-4};  //1  //-1
        int[] nums5 = {1,1,-1,-1,3};  //-1
        int[] nums6 = {1,2,4,8,16,32,64,128};  //82

        System.out.println(threeSumClosest(nums6,82));
    }

    /**
     * 双指针
     * AC
     * @param nums
     * @param target
     * @return
     */
    public static int threeSumClosest(int[] nums, int target) {
        int len = nums.length;
        Arrays.sort(nums);
        int closeSum = nums[0] + nums[1] + nums[2];
        for(int i=0;i<len;i++){
            int left = i+1;
            int right = len-1;
            while(left < right){
                int sum = nums[i] + nums[left] + nums[right];
                if(Math.abs(sum - target) < Math.abs(closeSum - target)){
                    closeSum = sum;
                }

                if(sum < target){
                    left++;
                }else if(sum > target){
                    right--;
                }else {
                    return target;
                }
            }
        }
        return closeSum;
    }
}
